/**
 * 
 */
package com.jm.utils.xml;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.jm.utils.StringHelper;
import com.jm.web.data.BaseDataEntities;
import com.jm.web.data.BaseDataEntity;
import com.jm.web.form.Paging;

/**
 * @author yanjie
 * Dec 14, 2011 10:44:13 AM
 */
public class DataEntitiesHandler extends DefaultHandler{
	public static final String VAR_ROOTNAME = "rows";
	public static final String VAR_COLUMNNODENAME = "column";
	public static final String VAR_ROWNODENAME = "row";
	
	private String value = null;
	private BaseDataEntities rows = null;
	private List columns = null;
	private int rowNumber = 0;
	private Paging paging = null;
	
	@Override
	public void startElement(String namespaceURI,String localName,String qName,Attributes attrs) throws SAXException{
		if(qName.equals(VAR_ROOTNAME)){
			this.rows = null;
			this.rows = new BaseDataEntities();
			
		}
		
		//栏位名称
		if(qName.equals(VAR_COLUMNNODENAME)){
			this.columns = new ArrayList();
		}  
	}  
	 
	 // 元素结尾
	 @Override
	 public void endElement(String namespaceURI,String localName,String qName) throws SAXException{	
		//栏位名称
		if(qName.equals(VAR_COLUMNNODENAME)){
			String[] cols = this.value.split(XmlUtils.strSplit);
			for (int i = 0; i < cols.length-1; i++) {
				this.columns.add(StringHelper.getValue(cols[i]));
			}
		}else if(qName.equals(VAR_ROWNODENAME)){//数据
			if(paging.getCurrentPage() >= 0){
				if(this.rowNumber < (paging.getCurrentPage()-1)*paging.getPageSize() 
						|| this.rowNumber >= (paging.getCurrentPage())*paging.getPageSize()){
					this.rowNumber++;
					return;
				}
			}
			
			String[] datas = this.value.split(XmlUtils.strSplit);
			BaseDataEntity row = new BaseDataEntity();
			for (int i = 0; i < datas.length-1; i++) {
				row.SetParamValue(
						StringHelper.getValue(this.columns.get(i))
						,StringHelper.getValue(datas[i]));
			}
			this.rows.add(row);
			this.rowNumber++;
		}
	 }  
	 
	 // 元素中间的文本数据
	 @Override
	 public void characters(char ch[],int start,int length) throws SAXException  
	 {  
	  value = new String(ch,start,length);  
	 }  
	 
	 //文档结尾
	 public void endDocument() throws SAXException{}

	public Paging getPaging() {
		return paging;
	}

	public void setPaging(Paging paging) {
		this.paging = paging;
	}

	public BaseDataEntities getRows() {
		return rows;
	}

	public void setRows(BaseDataEntities rows) {
		this.rows = rows;
	}  
}
